package com.hs.springboot_demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.springboot_demo.common.Result;
import com.hs.springboot_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.hs.springboot_demo.domain.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author d-will
 * @create 2022--02--24 15:52
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	UserService userService;

	@PostMapping("/save")
	public Result save(@RequestBody User user) {
		if (user.getPassword() == null) {
			user.setPassword("000000");
		}
		boolean b = userService.saveOrUpdate(user);
		if (b) {
			return Result.success();
		} else {
			return Result.error(1, "失败");
		}

	}

	@RequestMapping("getAll")
	@ResponseBody
	public List getAll() {
		// ArrayList<Object> list = new ArrayList<>();
		List<User> list1 = userService.list();
		return list1;
	}

	@GetMapping("/findPage")
	public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
	                       @RequestParam(defaultValue = "10") Integer pageSize,
	                       @RequestParam(defaultValue = "") String search) {

		Page<User> page = new Page<>(pageNum, pageSize);
		// userService.page(page, Wrappers.<User>lambdaQuery().like(User::getNickname,search));
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		if (StrUtil.isNotBlank(search)) {

			wrapper.like("nickname", search);
		}
		Page<User> page1 = userService.page(page, wrapper);

		return Result.success(page1);
	}

	@GetMapping("/delById")
	public Result delById(@RequestParam Integer id) {
		boolean b = userService.removeById(id);
		if (b) {

			return Result.success();
		} else {

			return Result.error(0, "失败了");
		}
	}

	@PostMapping("/login")
	public Result login(@RequestBody User user) {

		QueryWrapper<User> eq = new QueryWrapper<User>().eq("username", user.getUsername()).eq("password", user.getPassword());

		User one = userService.getOne(eq);
		if (one != null) {
			return Result.success(one);
		} else {
			return Result.error(1, "用户名或密码错误");
		}
	}

	@PostMapping("/register")
	public Result register(@RequestBody User user) {

		QueryWrapper<User> eq = new QueryWrapper<User>().eq("username", user.getUsername());

		User one = userService.getOne(eq);
		if (one == null) {
			boolean save = userService.save(user);
			if (save) {
				return Result.success();
			} else {
				return Result.error(1, "用户名或密码错误");
			}
		} else {
			return Result.error(1, "用户名或密码错误");
		}
	}

}
